package com.tastesport.chat.command;

import com.tastesport.chat.util.jwt.JwtUtil;
import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.http.HttpConst;
import org.jim.common.http.HttpRequest;
import org.jim.common.packets.Command;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.command.handler.processor.handshake.WsHandshakeProcessor;
import org.springframework.util.StringUtils;
import org.tio.core.ChannelContext;

/**
 * @author WChao
 */
public class DemoWsHandshakeProcessor extends WsHandshakeProcessor {

    @Override
    public void onAfterHandshaked(ImPacket packet, ChannelContext channelContext) throws Exception {
        LoginReqHandler loginHandler = (LoginReqHandler) CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
        HttpRequest request = (HttpRequest) packet;
//        String userid = StringUtils.isEmpty(request.getParams().get("userid")) ? null : (String) request.getParams().get("userid")[0];
        String groupid = StringUtils.isEmpty(request.getParams().get("groupid")) ? "0" : (String) request.getParams().get("groupid")[0];
        String token = StringUtils.isEmpty(request.getParams().get("token")) ? null : (String) request.getParams().get("token")[0];
        String userid = StringUtils.isEmpty(token) ? null : JwtUtil.getAccount(token);
//        System.out.println("request .. token[" + token + "] - userid[" + userid + "]");
//        System.out.println("request .. groupid[" + request.getParams().get("groupid")[0] + "]");
        LoginReqBody loginBody = new LoginReqBody(userid, groupid);

        byte[] loginBytes = JsonKit.toJsonBytes(loginBody);
        request.setBody(loginBytes);
        request.setBodyString(new String(loginBytes, HttpConst.CHARSET_NAME));
        ImPacket loginRespPacket = loginHandler.handler(request, channelContext);
        if (loginRespPacket != null) {
            ImAio.send(channelContext, loginRespPacket);
        }
    }
}
